const express=require('express')
const multer = require("multer");
const fs =require('fs')
const app = express()
//对上传的文件进行配置
var storage = multer.diskStorage({
	//指定文件上传到服务器的路径
	  destination: function (req, file, cb) {
		cb(null, __dirname+'/public/img')
	  },
	
	//指定上传到服务器文件的名称
	  filename: function (req, file, cb) {
		cb(null, file.fieldname + '-' + Date.now())
	  }
	})
	 
var upload = multer({ storage: storage })
var bodyParser = require('body-parser');/*post方法*/
app.use(bodyParser.json({limit : '2100000kb'}));// 添加json解析
app.use(bodyParser.urlencoded({extended: false}));
app.use('/user',require('./router/User.js'))
app.use('/news',require('./router/News.js'))
app.post('/uploadImg',upload.single("file"),function (req,res){
	switch (req.file.mimetype) {	//判断文件类型
		case 'image/pjpeg': extension_name = 'jpg';  break;
		case 'image/jpeg': extension_name = 'jpg'; break;
		case 'image/gif': extension_name = 'gif'; break;
		case 'image/png': extension_name = 'png'; break;
		case 'image/x-png': extension_name = 'png'; break;
		case 'image/bmp': extension_name = 'bmp'; break;
	}
	fs.rename(req.file.path,req.file.path+'.'+extension_name,(err)=>{
		if (err) {
			console.log('err:' + err);
		  } else {
			res.send({
				code:200,
				data:{
					message:'上传成功',
					icon:req.file.filename+'.'+extension_name
				}
			})
		  }
	})
});
app.get('/public/img/*',(req,res)=>{
    res.sendFile( __dirname + "/" + req.url );
})
app.listen(3000,'0.0.0.0',()=>{console.log('server has been run at port 3000')})